package com.ie.service.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ie.common.http.ResponseResult;
import com.ie.entity.CartEntity;
import com.ie.entity.GoodsEntity;
import com.ie.entity.OrderdetailEntity;
import com.ie.entity.OrdersEntity;
import com.ie.mapper.admin.OrderMapper;
import com.ie.service.before.CartService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
/**
 * @author xujia
 */
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrdersEntity> implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private CartService cartService;

    @Override
    public ResponseResult<Map<String, Object>> getAllOrders(OrdersEntity ordersEntity) {
        IPage<OrdersEntity> ipage = new Page<>(ordersEntity.getCurrentPage(), 5);
        LambdaQueryWrapper<OrdersEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        Integer id = ordersEntity.getId();
        if (id != null) {
            lambdaQueryWrapper.eq(OrdersEntity::getId, id);
            // 单表的分页查询在service层可以实现
        }
        IPage<OrdersEntity> pg = this.page(ipage, lambdaQueryWrapper);
        Map<String, Object> myres = new HashMap<>();
        myres.put("allOrders", pg.getRecords());
        myres.put("totalPage", pg.getPages());
        return ResponseResult.getSuccessResult(myres);

    }

    @Override
    public ResponseResult<List<Map<String, Object>>> getOrdersDetail(OrdersEntity ordersEntity) {
        return ResponseResult.getSuccessResult(orderMapper.getOrdersDetail(ordersEntity));
    }

    @Override
    public ResponseResult<OrdersEntity> submitOrder(OrdersEntity ordersEntity) {
        // 0:未支付；1：已支付
        ordersEntity.setStatus(0);
        ordersEntity.setOrderdate(new Date());
        save(ordersEntity);
        // 生成订单详情
        List<Integer> bgid = ordersEntity.getBgid();
        List<Integer> bshoppingnum = ordersEntity.getBshoppingnum();
        List<OrderdetailEntity> bods = new ArrayList<OrderdetailEntity>();
        List<GoodsEntity> ges = new ArrayList<GoodsEntity>();
        for (int i = 0; i < bgid.size(); i++) {
            OrderdetailEntity ot = new OrderdetailEntity();
            GoodsEntity ge = new GoodsEntity();
            ot.setOrderbasetableId(ordersEntity.getId());
            ot.setGoodstableId(bgid.get(i));
            ot.setShoppingnum(bshoppingnum.get(i));
            bods.add(ot);
            ge.setId(bgid.get(i));
            // 减少库存 90-14=76
            ge.setGstore(goodsService.getById(bgid.get(i)).getGstore() - bshoppingnum.get(i));
            ges.add(ge);
        }
        // 批量保存订单详情
        orderDetailService.saveBatch(bods);
        // 批量更新商品库存
        goodsService.updateBatchById(ges);
        CartEntity cartEntity = new CartEntity();
        cartEntity.setBusertableId((ordersEntity.getBusertableId()));
        cartService.clearCart(cartEntity);
        return ResponseResult.getSuccessResult(ordersEntity);
    }

    @Override
    public ResponseResult<Map<String, Object>> getOrdersByUid(OrdersEntity ordersEntity) {
        /**
         * 根据用户 ID 分页查询订单
         *
         * @param ordersEntity 封装分页参数 + busertableld
         * @return 统一返回结果
         */
        // 1. 创建分页对象（当前页，每页 5 条）
        IPage<OrdersEntity> iPage = new Page<>(ordersEntity.getCurrentPage(), 5);

        // 2. 构建查询条件：用户 id 相等，并按状态升序
        LambdaQueryWrapper<OrdersEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrdersEntity::getBusertableId, ordersEntity.getBusertableId())
                .orderByAsc(OrdersEntity::getStatus);
        // 3. 执行分页查询
        IPage<OrdersEntity> pg = page(iPage, wrapper);
        // 4. 组装返回数据
        Map<String, Object> myres = new HashMap<>();
        myres.put("ordersByUid", pg.getRecords()); // 当前页数据
        myres.put("totalPage", pg.getPages());     // 总页数
        // 5. 返回成功响应
        return ResponseResult.getSuccessResult(myres);
    }

    @Override
    public ResponseResult<Map<String, Object>> goPay(OrdersEntity ordersEntity) {
        ordersEntity.setStatus(1);
        if (updateById(ordersEntity)) {
            return ResponseResult.getMessageResult(null, "A001");
        }
        return ResponseResult.getMessageResult(null, "A002");
    }
}

